package org.sixtynine.stock.api;

import javax.annotation.PostConstruct;

import org.apache.log4j.Logger;
import org.sixtynine.stock.Constants;
import org.sixtynine.stock.ReturnData;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.ResourceHttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
public class ConnectionManager {

	/** base url of API */
	private String baseUrl;

	/** whether go to the service or get it from the mock */
	private boolean mock;

	private String id;
	private String code;

	/** connection timeout in miliseconds */
	private int connectionTimeout;
	
	private RestTemplate restTemplate = null;

	/** api constants */
	public static final int DATA_TYPE_SECTOR = 1;
	public static final int DATA_TYPE_STOCK = 2;

	public static final int DATA_SOURCE_TICKER = 1;
	public static final int DATA_SOURCE_RAW = 2;

	private static Logger logger = Logger.getLogger(ConnectionManager.class);

	@PostConstruct
	public void init() {
		restTemplate = restTemplate = new RestTemplate();
		restTemplate.getMessageConverters().add(
				new StringHttpMessageConverter());
		restTemplate.getMessageConverters().add(
				new MappingJacksonHttpMessageConverter());
		restTemplate.getMessageConverters().add(
				new ResourceHttpMessageConverter());
	}
	
   /* private ClientHttpRequestFactory clientHttpRequestFactory() {
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setReadTimeout(connectionTimeout);
        factory.setConnectTimeout(connectionTimeout);
        return factory;
    }*/

	/** get data from the API */
	public ReturnData<?> getData(String url, Class<?> clazz) {
		if (restTemplate == null) {
			init();
		}

		ReturnData<Object> returnData = new ReturnData<Object>(
				Constants.SUCCESS, "");

		if (!mock) {
			try {
				String requestUrl = baseUrl + url + getAccountDetails();

				logger.info("######### request url :" + requestUrl);
				Object obj = restTemplate.getForObject(requestUrl, clazz);
				returnData.setData(obj);
			} catch (Exception ex) {
				logger.error(ex.getMessage());
				returnData.setNo(Constants.ERROR);
				returnData.setMsg(ex.getMessage());
			}
		} else {
			returnData.setMsg("Service connection is ignored");
		}

		return returnData;
	}

	private String getAccountDetails() {
		StringBuilder sb = new StringBuilder();
		sb.append("&ID=" + id);
		sb.append("&CODE=" + code);

		return sb.toString();
	}

	public String getBaseUrl() {
		return baseUrl;
	}

	public void setBaseUrl(String baseUrl) {
		this.baseUrl = baseUrl;
	}

	public boolean isMock() {
		return mock;
	}

	public void setMock(boolean mock) {
		this.mock = mock;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public int getConnectionTimeout() {
		return connectionTimeout;
	}

	public void setConnectionTimeout(int connectionTimeout) {
		this.connectionTimeout = connectionTimeout;
	}

}
